package com.raorao.rpc.common.utils;

import com.raorao.rpc.common.constants.ConfigConstant;
import com.raorao.rpc.server.model.ConfigModel;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author raorao
 * @version 1.0
 * @description: bean对象属性工具类
 * @date 2021/12/10 15:19
 */
public class BeanPropertyUtils {
    /**
     * @description: 根据配置信息将配置更新到对应的bean对象中
     * @param: configModelMap
     * @param: obj
     * @return: void
     * @author raorao
     * @date: 2021/12/10 15:23
     */
    public static void changeBeanProperty(Map<String, ConfigModel> configModelMap,Object obj) throws Exception{
        String prefix="";
        //1、提取配置信息前缀
        Class<?> clazz = obj.getClass();
        ConfigurationProperties configurationProperties = clazz.getAnnotation(ConfigurationProperties.class);
        if(configurationProperties!=null&&!StringUtils.isEmpty(configurationProperties.prefix())){
            prefix=configurationProperties.prefix()+ ConfigConstant.CONFIG_DELIMITER;
        }
        //2、设置bean对象属性
        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        if(propertyDescriptors==null)return;
        for (PropertyDescriptor field:propertyDescriptors){
            String key=prefix+field.getName();
            if(configModelMap.containsKey(key)){
                ConfigModel configModel = configModelMap.get(key);
                Method setter = field.getWriteMethod();
                Class<?> propertyType = field.getPropertyType();
                Object val=propertyType.getConstructor(String.class).newInstance(configModel.getVal());
                setter.invoke(obj,val);
            }
        }
    }
}
